package org.shop.controller.app;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Address;
import org.shop.entity.Goods;
import org.shop.entity.Merchant;
import org.shop.entity.OrderGoods;
import org.shop.entity.OrderSettlements;
import org.shop.entity.Orders;
import org.shop.entity.SupplierGoods;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.AddressService;
import org.shop.service.GoodsService;
import org.shop.service.MerchantService;
import org.shop.service.OrderGoodsService;
import org.shop.service.OrderSettlementsService;
import org.shop.service.OrdersService;
import org.shop.service.ShoppingCardService;
import org.shop.service.SupplierGoodsService;
import org.shop.util.CommonUtil;
import org.shop.util.HttpClientUtil;
import org.shop.util.JsonUtils;
import org.shop.util.ObjUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class OrdersController {
	private static Logger logger = LogManager.getLogger(OrdersController.class);
	@Autowired
    private OrdersService ordersService;
	@Autowired
	private OrderGoodsService orderGoodsService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private ShoppingCardService shoppingCardService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private SupplierGoodsService supplierGoodsService;
	@Autowired
	private OrderSettlementsService orderSettlementsService;
	@Autowired
	private MerchantService merchantService;
	/**
	 * 商品直接提交订单
	 * @param req
	 * @return
	 */
	@RequestMapping("app/directOrder")
	@ResponseBody
	public Map<String, Object> directOrder(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String goodsId = req.getParameter("goodsId");
		String goodsCount = req.getParameter("goodsCount");//商品数量
		String orderPrice = req.getParameter("orderPrice");//总价
		String goodsSize = req.getParameter("goodsSize");//总价
		long date =  Calendar.getInstance().getTimeInMillis();//订单号
		//收件信息
		String userName = req.getParameter("userName");
		String userAddress = req.getParameter("userAddress");
		String userPhone = req.getParameter("userPhone");
		String orderRemarks = req.getParameter("orderRemarks");
		
		try {
			Goods goodsInfo = goodsService.selectByPrimaryKey(Long.parseLong(goodsId));
			//插入订单表
			Orders order = new Orders();
			order.setOrderNo(String.valueOf(date));//订单号
//			order.setUserId(ud.getUserId());//用户Id
			order.setUserId(ud.getUserId());//用户Id
			order.setMerchantId(goodsInfo.getMerchantId());//商家Id
//			order.setMerchantId((long)1);//商家Id
			order.setOrderPrice(goodsInfo.getGoodsPrice().multiply(new BigDecimal(goodsCount)));//订单金额
			order.setOrderCount(Integer.parseInt(goodsCount));//商品数量
			order.setUserName(userName);//收件人姓名
			order.setUserAddress(userAddress);//收件人地址
			order.setUserPhone(userPhone);//收件人电话
			order.setOrderRemarks(orderRemarks);//订单备注
			ordersService.insertSelective(order);
			
			//插入订单商品表
			OrderGoods orderGoods = new OrderGoods();
			orderGoods.setOrderId(order.getOrderId());//订单Id
			orderGoods.setGoodsId(Long.parseLong(goodsId));//商品Id
			orderGoods.setGoodsName(goodsInfo.getGoodsName());//商品名称
			orderGoods.setGoodsPrice(goodsInfo.getGoodsPrice());//商品单价
			orderGoods.setGoodsCount(Integer.parseInt(goodsCount));//商品数量
			orderGoods.setGoodsThums(goodsInfo.getGoodsThums());//商品缩略图
			orderGoods.setGoodsSize(goodsSize);//商品规格
			if(ObjUtil.isNotNullAndEmpty(goodsInfo.getSupplierGoodsId())) {
				SupplierGoods supplierGoods = supplierGoodsService.selectByPrimaryKey(goodsInfo.getSupplierGoodsId());
				orderGoods.setSupplierGoodsId(supplierGoods.getSupplierGoodsId());
				orderGoods.setSupplierGoodsName(supplierGoods.getSupplierGoodsName());
				orderGoods.setSupplierGoodsPrice(supplierGoods.getSupplierGoodsPrice());
				orderGoods.setSupplierGoodsThums(supplierGoods.getSupplierGoodsThums());
			}
			orderGoodsService.insertSelective(orderGoods);
			//修改库存数量
			goodsInfo.setGoodsId(Long.parseLong(goodsId));
			goodsInfo.setGoodsStock(goodsInfo.getGoodsStock() - Integer.parseInt(goodsCount));
			goodsInfo.setGoodsSales(goodsInfo.getGoodsSales() + Integer.parseInt(goodsCount));;
			goodsService.updateByPrimaryKeySelective(goodsInfo);
			map.put("state", 1);
			map.put("msg", "提交成功");
		} catch(Exception e) {
			e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "提交失败");
		}
		return map;
	}
	
	/**
	 * 购物车订单(方案一：一个商品一条订单，订单号相同)
	 * @param req
	 * @return
	 */
//	@RequestMapping("shoppingCardOrder")
//	@ResponseBody
//	public Map<String, Object> shoppingCardOrder(HttpServletRequest req){
//		Map<String, Object> map = new HashMap<String, Object>();
//		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		String ids = req.getParameter("goodsIds");
//		String orderPrice = req.getParameter("orderPrice");
//		long date =  Calendar.getInstance().getTimeInMillis();//订单号
//		//收件信息
//		String userName = req.getParameter("userName");
//		String userAddress = req.getParameter("userAddress");
//		String userPhone = req.getParameter("userPhone");
//		String orderRemarks = req.getParameter("orderRemarks");
//		try {
//			String[] idArray = ids.split(",");
//			for (String id : idArray) {
//				Orders order = new Orders();
//				order.setOrderNo(String.valueOf(date));//订单号
//				order.setUserId(ud.getUserId());//用户Id
//				order.setOrderPrice(new BigDecimal(orderPrice));//订单金额
//				order.setUserName(userName);//收件人姓名
//				order.setUserAddress(userAddress);//收件人地址
//				order.setUserPhone(userPhone);//收件人电话
//				order.setOrderRemarks(orderRemarks);//订单备注
//				ordersService.insertSelective(order);
//				Map<String, Object> params = new HashMap<String, Object>();
//				params.put("userId", ud.getUserId());
//				params.put("goodsId", id);
//				ShoppingTrolley shoppingTrolley = shoppingCardService.getShoppingCardGoods(params);
//				Goods goodsInfo = goodsService.selectByPrimaryKey(Long.parseLong(id));
//				OrderGoods orderGoods = new OrderGoods();
//				orderGoods.setOrderId(order.getOrderId());//订单Id
//				orderGoods.setGoodsId(Long.parseLong(id));//商品Id
//				orderGoods.setGoodsName(goodsInfo.getGoodsName());//商品名称
//				orderGoods.setGoodsPrice(shoppingTrolley.getUnitPrice());//商品单价
//				orderGoods.setGoodsCount(shoppingTrolley.getOrderCount());//商品数量
//				orderGoods.setGoodsThums(goodsInfo.getGoodsThums());//商品缩略图
//				orderGoodsService.insertSelective(orderGoods);
//				order.setMerchantId(goodsInfo.getMerchantId());//商家Id
//				ordersService.updateByPrimaryKeySelective(order);
//				shoppingCardService.delShoppingCardGoods(params);
//			}
//			map.put("state", 1);
//			map.put("msg", "提交成功");
//		} catch(Exception e) {
//			e.printStackTrace();
//    		logger.error(e);
//    		map.put("state", 0);
//    		map.put("msg", "提交失败");
//		}
//		return map;
//	}
	
	/**
	 * 购物车提交订单（方案二：每个商家多个商品一个订单，每个商家订单号不同）
	 * @param req
	 * @return
	 */
	@RequestMapping("app/shoppingCardOrder")
	@ResponseBody
	public Map<String, Object> shoppingCardOrder(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		long orderNo =  Calendar.getInstance().getTimeInMillis();//订单号
		//收件信息
		String userName = req.getParameter("userName");
		String userAddress = req.getParameter("userAddress");
		String userPhone = req.getParameter("userPhone");
		String orderRemarks = req.getParameter("orderRemarks");
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", ud.getUserId());
			params.put("userCheck", 1);
			//获取我选中的购物车商品
			List<Map<String, Object>> list = shoppingCardService.getCheckShoppingCardList(params);
			
			Long orderId = null;
			
			for (int i=0;i<list.size();i++) {
				Map<String, Object> m = new HashMap<String, Object>();
				m.put("merchantId", list.get(i).get("merchantId"));
				m.put("orderNo", orderNo);
				Orders orderInfo = ordersService.getOrder(m);
				Orders order = new Orders();
				
				if(orderInfo == null) {
					orderNo =  Calendar.getInstance().getTimeInMillis();//订单号
					order.setOrderNo(String.valueOf(orderNo));//订单号
//					order.setUserId(ud.getUserId());//用户Id
					order.setUserId(ud.getUserId());//用户Id
					order.setOrderPrice(new BigDecimal(list.get(i).get("orderPrice").toString()));//订单金额
					order.setUserName(userName);//收件人姓名
					order.setUserAddress(userAddress);//收件人地址
					order.setUserPhone(userPhone);//收件人电话
					order.setOrderRemarks(orderRemarks);//订单备注
					order.setMerchantId(Long.parseLong(list.get(i).get("merchantId").toString()));
					ordersService.insertSelective(order);
					orderId = order.getOrderId();
				}else {
					
					orderInfo.setOrderPrice(orderInfo.getOrderPrice().add(new BigDecimal(list.get(i).get("unitPrice").toString()).multiply(new BigDecimal(list.get(i).get("orderCount").toString()))));
					ordersService.updateByPrimaryKey(orderInfo);
				}
				//插入订单商品表
				OrderGoods orderGoods = new OrderGoods();
				orderGoods.setOrderId(orderId);//订单Id
				orderGoods.setGoodsId(Long.parseLong(list.get(i).get("goodsId").toString()));//商品Id
				orderGoods.setGoodsName(list.get(i).get("goodsName").toString());//商品名称
				orderGoods.setGoodsPrice(new BigDecimal(list.get(i).get("unitPrice").toString()));//商品单价
				orderGoods.setGoodsCount(Integer.parseInt(list.get(i).get("orderCount").toString()));//商品数量
				orderGoods.setGoodsThums(list.get(i).get("goodsThums").toString());//商品缩略图
				if(ObjUtil.isNotNullAndEmpty(list.get(i).get("goodsSize"))) {
					orderGoods.setGoodsSize(list.get(i).get("goodsSize").toString());
				}
				if(ObjUtil.isNotNullAndEmpty(list.get(i).get("supplierGoodsId"))) {
					SupplierGoods supplierGoods = supplierGoodsService.selectByPrimaryKey(Long.parseLong(list.get(i).get("supplierGoodsId").toString()));
					orderGoods.setSupplierGoodsId(supplierGoods.getSupplierGoodsId());
					orderGoods.setSupplierGoodsName(supplierGoods.getSupplierGoodsName());
					orderGoods.setSupplierGoodsPrice(supplierGoods.getSupplierGoodsPrice());
					orderGoods.setSupplierGoodsThums(supplierGoods.getSupplierGoodsThums());
				}
				orderGoodsService.insertSelective(orderGoods);
				//修改库存数量
				Goods goodsInfo = goodsService.selectByPrimaryKey(Long.parseLong(list.get(i).get("goodsId").toString()));
				goodsInfo.setGoodsStock(goodsInfo.getGoodsStock() - Integer.parseInt(list.get(i).get("orderCount").toString()));
				goodsInfo.setGoodsSales(goodsInfo.getGoodsSales() + Integer.parseInt(list.get(i).get("orderCount").toString()));
				goodsService.updateByPrimaryKeySelective(goodsInfo);
				shoppingCardService.delShoppingCardGoods(params);
				
			}
			map.put("state", 1);
			map.put("msg", "提交成功");
		} catch(Exception e) {
			e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "提交失败");
		}
		return map;
	}
	
	
	/**
	 * 用户获取所有订单
	 * @return
	 */
	@RequestMapping("app/getUserOrderList")
	public String getUserOrderList(HttpServletRequest req){
		List<Map<String,Object>> orderList = new ArrayList<Map<String,Object>>();
//		Map<String,Object> paramMap1 = new HashMap<String,Object>();
        String orderNo = req.getParameter("orderNo");
        String goodsName = req.getParameter("goodsName");
        String orderStatus = req.getParameter("orderStatus");
        String payNo = req.getParameter("payNo");
//        Orders orderInfo = null;
        logger.info("**********进来order了******************");
        logger.info("**********payNo******************"+payNo);
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			if(payNo!=null&&payNo!="") {
//				paramMap1.put("orderNo", payNo);
//				orderInfo = ordersService.getOrder(paramMap1);
//			    if(orderInfo.getIsPay()==1&&orderInfo.getPayFrom()==2&&orderInfo.getOrderStatus()>=3) {
//	            	req.setAttribute("ifSuccess", 1);
//	            	req.setAttribute("orderInfo", orderInfo);
//	            	req.setAttribute("orderNo", orderInfo.getOrderNo());
//	            	logger.info("**********订单成功支付******************------------");
//	            	logger.info("**********订单状态******************------------"+orderInfo.getOrderStatus());
//	            	logger.info("**********是否支付******************------------"+orderInfo.getIsPay());
//	            	logger.info("**********支付方式******************------------"+orderInfo.getPayFrom());
//	            }else if(orderInfo.getOrderStatus()<3){
//	            	logger.info("**********订单没有支付******************------------");
//	            	req.setAttribute("ifSuccess", 2);
//	            	req.setAttribute("orderNo", orderInfo.getOrderNo());
//	            	logger.info("**********订单状态******************------------"+orderInfo.getOrderStatus());
//	            	logger.info("**********是否支付******************------------"+orderInfo.getIsPay());
//	            	logger.info("**********支付方式******************------------"+orderInfo.getPayFrom());
//	            }
				logger.info("**********订单号******************------------"+payNo);
				req.setAttribute("orderNo", payNo);
			}else {
				logger.info("**********订单管理进入******************------------");
				req.setAttribute("ifSuccess", 3);
			}
            Map<String, Object> paramMap = new HashMap<String, Object>();
//            paramMap.put("userId", ud.getUserId());
            paramMap.put("userId", ud.getUserId());
            paramMap.put("orderNo", orderNo);
            paramMap.put("goodsName", goodsName);
            paramMap.put("orderStatus", orderStatus);
            orderList = ordersService.getUserOrderList(paramMap);
            req.setAttribute("orderList", orderList);
            logger.info("**********进来order11111111了******************------------");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
		return "app/order";
	}
	
	/**
	 * 用户取消订单
	 * @return
	 */
	@RequestMapping("app/userCancelOrder")
	@ResponseBody
	public Map<String, Object> userCancelOrder(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
		String orderId = req.getParameter("orderId");
		try {
			Orders orders = new Orders();
			orders.setOrderId(Long.parseLong(orderId));
			orders.setOrderStatus((byte)2);
			ordersService.updateByPrimaryKeySelective(orders);
			map.put("state", 1);
			map.put("msg", "取消成功");
		} catch(Exception e) {
			map.put("state", 0);
			map.put("msg", "取消失败");
			logger.error(e);
		}
		return map;
	}
	
	/**
	 * 用户删除订单
	 * @return
	 */
	@RequestMapping("app/userDelOrder")
	@ResponseBody
	public Map<String, Object> userDelOrder(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
		String orderId = req.getParameter("orderId");
		try {
			Orders orders = new Orders();
			orders.setOrderId(Long.parseLong(orderId));
			orders.setState((byte)0);
			ordersService.updateByPrimaryKeySelective(orders);
			map.put("state", 1);
			map.put("msg", "删除成功");
		} catch(Exception e) {
			map.put("state", 0);
			map.put("msg", "删除失败");
			logger.error(e);
		}
		return map;
	}
	
	/**
	 * 用户确认收货
	 * @return
	 */
	@RequestMapping("app/userConfirmReceipt")
	@ResponseBody
	public Map<String, Object> userConfirmReceipt(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
		String orderId = req.getParameter("orderId");
		try {
			Orders orders = new Orders();
			orders.setOrderId(Long.parseLong(orderId));
			orders.setOrderStatus((byte)5);
			orders.setReceiveTime(new Date());
			int num = ordersService.updateByPrimaryKeySelective(orders);
			//确认收货成功插入订单结算记录
			if(num > 0) {
				Orders o = ordersService.selectByPrimaryKey(Long.parseLong(orderId));
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("merchantId", o.getMerchantId());
				OrderSettlements os = orderSettlementsService.getOrderSettlements(params);
				
				Merchant merchant = merchantService.selectByPrimaryKey(o.getMerchantId());
				//如果店铺已存在
				if(ObjUtil.isNotNullAndEmpty(os)) {
					//如果是自营店铺
					if(merchant.getMerchantType() == 3) {
						//自营和供应商的所有商品总差价
						BigDecimal commissionFee = BigDecimal.ZERO;
						Map<String, Object> m = new HashMap<String, Object>();
						m.put("orderId", o.getOrderId());
						List<Map<String,Object>> list = orderGoodsService.getOrderGoodsList(m);
						if(list.size() > 0) {
							for(int i = 0; i < list.size(); i++) {
								//供应商
								OrderSettlements supplierSettlements = new OrderSettlements();
								Map<String, Object> orderGoodsMap = list.get(i);
								//通过供应商id获取结算信息
								Map<String, Object> params2 = new HashMap<String, Object>();
								params2.put("supplierId", orderGoodsMap.get("supplierId"));
								OrderSettlements supplierOrderSettlements = orderSettlementsService.getOrderSettlements(params2);
								//如果供应商已存在
								if(ObjUtil.isNotNullAndEmpty(supplierOrderSettlements)) {
									supplierSettlements.setSettlementId(supplierOrderSettlements.getSettlementId());
									supplierSettlements.setSupplierPrice(supplierOrderSettlements.getSupplierPrice().add(new BigDecimal(orderGoodsMap.get("supplierGoodsPrice").toString())));
									supplierSettlements.setUpdateDate(new Date());
									orderSettlementsService.updateByPrimaryKeySelective(supplierSettlements);
								}else {
									supplierSettlements.setSupplierId(Long.parseLong(orderGoodsMap.get("supplierId").toString()));
									supplierSettlements.setSupplierPrice(new BigDecimal(orderGoodsMap.get("supplierGoodsPrice").toString()));
									orderSettlementsService.insertSelective(supplierSettlements);
								}
								//单个商品的差价
								BigDecimal poundageMoney = new BigDecimal(orderGoodsMap.get("goodsPrice").toString()).subtract(new BigDecimal(orderGoodsMap.get("supplierGoodsPrice").toString()));
								commissionFee = commissionFee.add(poundageMoney.multiply(new BigDecimal(orderGoodsMap.get("goodsCount").toString())));
							}
							OrderSettlements orderSettlements = new OrderSettlements();
							orderSettlements.setSettlementId(os.getSettlementId());
							orderSettlements.setMerchantPrice(os.getMerchantPrice().add(commissionFee));
							orderSettlements.setUpdateDate(new Date());
							orderSettlementsService.updateByPrimaryKeySelective((orderSettlements));
						}
						
					}else {
						OrderSettlements orderSettlements = new OrderSettlements();
						orderSettlements.setSettlementId(os.getSettlementId());
						orderSettlements.setMerchantId(o.getMerchantId());
						orderSettlements.setMerchantPrice(os.getMerchantPrice().add(o.getOrderPrice()));
						orderSettlements.setUpdateDate(new Date());
						orderSettlementsService.updateByPrimaryKeySelective(orderSettlements);
					}
				}else {
					//如果是自营店铺
					if(merchant.getMerchantType() == 3) {
						//自营和供应商的所有商品总差价
						BigDecimal commissionFee = BigDecimal.ZERO;
						Map<String, Object> m = new HashMap<String, Object>();
						m.put("orderId", o.getOrderId());
						List<Map<String,Object>> list = orderGoodsService.getOrderGoodsList(m);
						if(list.size() > 0) {
							for(int i = 0; i < list.size(); i++) {
								//供应商
								OrderSettlements supplierSettlements = new OrderSettlements();
								Map<String, Object> orderGoodsMap = list.get(i);
								//通过供应商id获取结算信息
								Map<String, Object> params2 = new HashMap<String, Object>();
								params2.put("supplierId", orderGoodsMap.get("supplierId"));
								OrderSettlements supplierOrderSettlements = orderSettlementsService.getOrderSettlements(params2);
								//如果供应商已存在
								//供应商商品总金额(单价乘以数量)
								BigDecimal supplierGoodsPriceCount = new BigDecimal(orderGoodsMap.get("supplierGoodsPrice").toString()).multiply(new BigDecimal(orderGoodsMap.get("goodsCount").toString()));
								if(ObjUtil.isNotNullAndEmpty(supplierOrderSettlements)) {
									supplierSettlements.setSettlementId(supplierOrderSettlements.getSettlementId());
									supplierSettlements.setSupplierPrice(supplierOrderSettlements.getSupplierPrice().add(supplierGoodsPriceCount));
									supplierSettlements.setUpdateDate(new Date());
									orderSettlementsService.updateByPrimaryKeySelective(supplierSettlements);
								}else {
									supplierSettlements.setSupplierId(Long.parseLong(orderGoodsMap.get("supplierId").toString()));
									supplierSettlements.setSupplierPrice(supplierGoodsPriceCount);
									orderSettlementsService.insertSelective(supplierSettlements);
								}
								
								//单个商品的差价
								BigDecimal poundageMoney  = new BigDecimal(orderGoodsMap.get("goodsPrice").toString()).subtract(new BigDecimal(orderGoodsMap.get("supplierGoodsPrice").toString()));
								commissionFee = commissionFee.add(poundageMoney.multiply(new BigDecimal(orderGoodsMap.get("goodsCount").toString())));
								
							}
							//自营店铺
							OrderSettlements orderSettlements = new OrderSettlements();
							orderSettlements.setMerchantId(o.getMerchantId());
							orderSettlements.setMerchantPrice(commissionFee);
							orderSettlementsService.insertSelective(orderSettlements);
						}
						
					}else {
						OrderSettlements orderSettlements = new OrderSettlements();
						orderSettlements.setMerchantId(o.getMerchantId());
						orderSettlements.setMerchantPrice(o.getOrderPrice());
						orderSettlementsService.insertSelective(orderSettlements);
					}
					
				}
			}
			map.put("state", num);
			map.put("msg", "确认收货成功");
		} catch(Exception e) {
			map.put("state", 0);
			map.put("msg", "确认收货失败");
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	
	/**
	 * 用户确认订单
	 * @return
	 */
	@RequestMapping("app/userAffirmOrder")
	public String userAffirmOrder(HttpServletRequest req){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			
			params.put("userId", ud.getUserId());
			params.put("userCheck", 1);
			//获取我选中的购物车商品
			List<Map<String, Object>> list = shoppingCardService.getShoppingCardList(params);
//			BigDecimal orderPricre = null;
//			for(int i=0;i<list.size();i++) {
//				Map<String,Object> map = list.get(i);
//				orderPricre = orderPricre.add(new BigDecimal(map.get("orderPrice").toString()));
//			}
			BigDecimal orderPrice = BigDecimal.ZERO;
			
//			for (Map<String, Object> map : list) {
//				orderPrice = orderPrice.add(new BigDecimal(map.get("orderPrice").toString()));
//				
//			}
			
			//获取默认地址传前台
			Address personDefaultAddress = addressService.getPersonDefaultAddress(ud.getUserId());
			int  orderCount = 0;
			for (Map<String, Object> map : list) {
				List<Map<String, Object>> m = (List<Map<String, Object>>) map.get("shoppingGoodsList");
				for (Map<String, Object> map2 : m) {
					orderPrice = orderPrice.add(new BigDecimal(map2.get("orderPrice").toString()));
					orderCount += Integer.parseInt(map2.get("orderCount").toString()) ;
				}
			}
			
			req.setAttribute("personDefaultAddress", personDefaultAddress);
			req.setAttribute("orderList", list);
			req.setAttribute("orderPricre", orderPrice);
			req.setAttribute("orderCount", orderCount);
		} catch(Exception e) {
			e.printStackTrace();
    		logger.error(e);
		}
		return "app/affirmOrder";
	}
	
	/**
	 * 查看是否支付成功
	 * @param req
	 * @return
	 */
	@RequestMapping("app/ifPaySuccess")
	@ResponseBody
	public Map<String,Object> ifPaySuccess(HttpServletRequest req){
		Map<String,Object> paramMap1 = new HashMap<String,Object>();
		Map<String,Object> map = new HashMap<String,Object>();
		String payNo = req.getParameter("orderNo");
		Orders orderInfo = null;
		try {
			if(payNo!=null&&payNo!="") {
				paramMap1.put("orderNo", payNo);
				orderInfo = ordersService.getOrder(paramMap1);
			    if(orderInfo.getIsPay()==1&&orderInfo.getPayFrom()==2&&orderInfo.getOrderStatus()>=3) {
	            	map.put("msg", 1);
	            	logger.info("app/ifPaySuccess**********订单成功支付******************------------");
	            	logger.info("app/ifPaySuccess**********订单状态******************------------"+orderInfo.getOrderStatus());
	            	logger.info("app/ifPaySuccess**********是否支付******************------------"+orderInfo.getIsPay());
	            	logger.info("app/ifPaySuccess**********支付方式******************------------"+orderInfo.getPayFrom());
	            }else if(orderInfo.getOrderStatus()<3){
	            	logger.info("app/ifPaySuccess**********订单没有支付******************------------");
	            	map.put("msg", 0);
	            	logger.info("app/ifPaySuccess**********订单状态******************------------"+orderInfo.getOrderStatus());
	            	logger.info("app/ifPaySuccess**********是否支付******************------------"+orderInfo.getIsPay());
	            	logger.info("app/ifPaySuccess**********支付方式******************------------"+orderInfo.getPayFrom());
	            }
			}else {
				map.put("msg", 0);
			}
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
}
